package com.bruce.tool.web.filter.core;

import com.bruce.tool.common.util.string.JsonUtils;
import com.bruce.tool.web.core.vo.ErrorCode;
import com.bruce.tool.web.core.vo.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Executable;
import java.lang.reflect.Type;
import java.util.Optional;

/**
 * 功能 :
 *
 * @author : Bruce(刘正航) 11:03 上午 2020/1/8
 */
@ControllerAdvice
public class JsonResultResponseAdvice implements ResponseBodyAdvice<Object> {

    @Value("${tool.response.json.advice}")
    private String filterPackage;

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        if (StringUtils.isBlank(filterPackage)) {
            return true;
        }
        String requestPackage = Optional.ofNullable(methodParameter.getMethod())
                .map(Executable::getAnnotatedReceiverType)
                .map(AnnotatedType::getType)
                .map(Type::getTypeName)
                .orElse("");
        return requestPackage.startsWith(filterPackage);
    }


    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        JsonResult result = new JsonResult();
        result.setCode(ErrorCode.SUCCESS);
        result.setMessage("请求成功");
        result.setData(body);
        if (body instanceof String) {
            return JsonUtils.objToStr(result);
        }
        return result;
    }
}
